;layui.define(function(e) {
    layui.use(['table','layer','form','laydate'], function(){
        var $ = layui.$
            ,layer = layui.layer
            ,form = layui.form
            ,table = layui.table
            ,laydate = layui.laydate;
        //展示已知数据
        var res=[{
            "dealerName": "北京朝阳嘉伟经销商",
            "storeName":[{
                "store_item": "10001"
                ,"store_name": "杜甫"
                ,"province": "xianxin@layui.com"
                ,"city": "男"
                ,"county": "浙江杭州"
                ,"store_address": "人生恰似一场修行"
                ,"name_legal": "116"
                ,"sex_legal": "116"
                ,"telephone_legal": "116"
                ,"name_reality": "116"
                ,"sex_reality": "116"
                ,"telephone_reality": "116"
                ,"createTime": "116"
            },{
                "store_item": "10001"
                ,"store_name": "杜甫"
                ,"province": "xianxin@layui.com"
                ,"city": "男"
                ,"county": "浙江杭州"
                ,"store_address": "人生恰似一场修行"
                ,"name_legal": "116"
                ,"sex_legal": "116"
                ,"telephone_legal": "116"
                ,"name_reality": "116"
                ,"sex_reality": "116"
                ,"telephone_reality": "116"
                ,"createTime": "116"
            }]
        },{
            "dealerName": "北京朝阳嘉伟经销商",
            "storeName":[{
                "store_item": "10001"
                ,"store_name": "杜甫"
                ,"province": "xianxin@layui.com"
                ,"city": "男"
                ,"county": "浙江杭州"
                ,"store_address": "人生恰似一场修行"
                ,"name_legal": "116"
                ,"sex_legal": "116"
                ,"telephone_legal": "116"
                ,"name_reality": "116"
                ,"sex_reality": "116"
                ,"telephone_reality": "116"
                ,"createTime": "116"
            }]
        }];
        var dealerData = [];
        for(let i=0;i<res.length;i++){
            dealerData.push({store_item:'经销商名称:',store_name:res[i].dealerName});
            for(let j=0;j<res[i].storeName.length;j++){
                dealerData.push(res[i].storeName[j])
            }
        }
       var dealer1 = table.render({
            elem: '#dealer1'
            ,cols: [[ //标题栏
                {field: 'store_item', title: '门店编号',minWidth:110,templet:'#storeItem'}
                ,{field: 'store_name', title: '门店名称',minWidth:200,}
                ,{field: 'province', title: '省'}
                ,{field: 'city', title: '市'}
                ,{field: 'county', title: '县/区'}
                ,{field: 'store_address', title: '门店详细地址'}
                ,{field: 'name_legal', title: '法人姓名'}
                ,{field: 'sex_legal', title: '法人性别'}
                ,{field: 'telephone_legal', title: '法人电话'}
                ,{field: 'name_reality', title: '实际控制人姓名'}
                ,{field: 'sex_reality', title: '实际控制人性别'}
                ,{field: 'telephone_reality', title: '实际控制人电话'}
                ,{field: 'createTime', title: '创建日期'}
                ,{field: 'tool',title: '操作', minWidth:200, align:'center', toolbar: '#operationMangerBar'}
            ]]
           ,height:'full-350'
            ,cellMinWidth: 120
            ,data: dealerData
            ,page: true //是否显示分页
           ,done: function (res, curr, count) {
               layuiRowspan('store_name','province','city','county','store_address','name_legal','sex_legal','telephone_legal','name_reality','sex_reality','telephone_reality',1);
            }
       });
       var look = table.render({
           elem:'#personnelFile'
           ,cols:[[
               {filed:'position',title:'职位'}
               ,{filed:'name',title:'姓名'}
               ,{filed:'sex',title:'性别'}
               ,{filed:'telephone',title:'电话'}
               ,{filed:'age',title:'年龄'}
               ,{filed:'degree',title:'学历'}
               ,{filed:'professional',title:'专业'}
               ,{filed:'working_years',title:'工龄'}
               ,{filed:'hire_date',title:'入职日期'}
               ,{filed:'tool',title:'操作', toolbar: '#personnelFileBar'}
           ]]
           ,height:'full-350'
           ,cellMinWidth: 120
           ,data: [{"position":"职位"
                   ,"name":"姓名"
                   ,"sex":"性别"
                   ,"telephone":"132456"
                   ,"age":"100"
                   ,"degree":"早教"
                   ,"professional":"专业"
                   ,"working_years":"专业"
                   ,"hire_date":"专业"
           },{
                    "position":"职位"
                   ,"name":"姓名"
                   ,"sex":"性别"
                   ,"telephone":"132456"
                   ,"age":"100"
                   ,"degree":"早教"
                   ,"professional":"专业"
                   ,"working_years":"专业"
                   ,"hire_date":"专业"}
           ]
           ,page: true //是否显示分页
       })
        //监听工具条
        table.on('tool(dealer1ListTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'dealerEdit'){
                dealerEdit();
            } else if(obj.event === 'look'){
                var index = layer.open({
                    type: 2
                    ,id: (new Date()).valueOf()
                    ,title: '查看'
                    ,content: 'look.html'
                    ,area: ['500px', '500px']
                    ,btn: ['保存', '取消']
                    ,maxmin: true
                    ,success: function(layero, index){
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
//                         var paramId=body.find("input[name='id']");
//                         paramId.val(111);
                    }
                    ,yes: function (layero, index) {
                        // layer.alert("保存按钮");
                        return false //开启该代码可禁止点击该按钮关闭
                    }
                    ,btn2: function (layero, index) {
                        layer.alert("取消按钮")
                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });
                layer.full(index);
            }else if(obj.event === 'edit'){
                storeEdit()
            }else if(obj.event === 'recover'){
                layer.confirm('确定恢复吗?', function(index){
                    layer.close(index);
                });
            }else if(obj.event === 'delete'){
             $("#alert_select").show();
             $("#alert_select .layui-layer-btn0").click(function () {
                 layer.confirm('确定注销吗?', function(index){
                     alert($("#alert_select").find("select").val());
                     $("#alert_select").hide();
                     layer.close(index);
                 });
             })
            $("#alert_select .layui-layer-btn2").click(function () {
                $("#alert_select").hide();
            })
            }
        });
        table.on('tool(personnelFiles)', function(obj){
            var data = obj.data;
            if(obj.event === 'personnelFileLook'){
                var index = layer.open({
                    type: 2
                    ,id: (new Date()).valueOf()
                    ,title: '查看'
                    ,content: 'inspectorFiless.html'
                    ,area: ['500px', '500px']
                    ,btn: ['确定', '取消']
                    ,maxmin: true
                    ,success: function(layero, index){
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
                    }
                    ,yes: function (layero, index) {
                        // layer.alert("保存按钮");
                        return false //开启该代码可禁止点击该按钮关闭
                    }
                    ,btn2: function (layero, index) {
                        layer.alert("取消按钮")
                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });
                layer.full(index);
            }
        });

        var $ = layui.$, active = {
            getCheckData: function(){ //获取选中数据
                var checkStatus = table.checkStatus('dealer1')
                    ,data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
            ,getCheckLength: function(){ //获取选中数目
                var checkStatus = table.checkStatus('dealer1')
                    ,data = checkStatus.data;
                layer.msg('选中了：'+ data.length + ' 个');
            }
        };

        $('.layadmin-takerates .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#date'
        });
        $("#addDealer").click(function () {
            dealerEdit()
        })
        $("#addStore").click(function () {
            storeEdit()
        })
        $(".dealer_head").parent().css({"padding-right":"0","text-align":"right"}).parent().parent().css({"background-color":"#e9f5fe"});
        //执行一个laydate日期实例
        laydate.render({
            elem: '#date'
        });
        form.render()
        function dealerEdit() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑'
                ,content: 'dealerEdit.html'
                ,area: ['500px', '500px']
                ,btn: ['保存', '取消']
                ,maxmin: true
                ,success: function(layero, index){
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
//                         var paramId=body.find("input[name='id']");
//                         paramId.val(111);
                }
                ,yes: function (layero, index) {
                     layer.alert("确定按钮");
                    return false //开启该代码可禁止点击该按钮关闭
                }
                ,btn2: function (layero, index) {
                    layer.alert("取消按钮")
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
            layer.full(index);
        }
        function storeEdit() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑'
                ,content: 'storeEdit.html'
                ,area: ['500px', '500px']
                ,btn: ['保存', '取消']
                ,maxmin: true
                ,success: function(layero, index){
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
//                         var paramId=body.find("input[name='id']");
//                         paramId.val(111);
                }
                ,yes: function (layero, index) {
                    layer.alert("确定按钮");
                    return false //开启该代码可禁止点击该按钮关闭
                }
                ,btn2: function (layero, index) {
                    layer.alert("取消按钮")
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
            layer.full(index);
        }
        /**
         * 合并单元格*/
        function layuiRowspan() {
            var execRowspan = function(fieldName,index,flag){
                // 1为不冻结的情况，左侧列为冻结的情况
                let fixedNode = index=="1"?$(".layui-table-body")[index - 1]:(index=="3"?$(".layui-table-fixed-r"):$(".layui-table-fixed-l"));
                // 左侧导航栏不冻结的情况
                let child = $(fixedNode).find("td");
                let childFilterArr = [];
                // 获取data-field属性为fieldName的td
                for(let i = 0; i < child.length; i++){
                    if(child[i].getAttribute("data-field") == fieldName){
                        childFilterArr.push(child[i]);
                    }
                }
                // 获取td的个数和种类
                let childFilterTextObj = {};
                for(let i = 0; i < childFilterArr.length; i++){
                    let childText = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;
                    if(childFilterTextObj[childText] == undefined){
                        childFilterTextObj[childText] = 1;
                    }else{
                        let num = childFilterTextObj[childText];
                        childFilterTextObj[childText] = num*1 + 1;
                    }
                }
                let canRowspan = true;
                let maxNum;//以前列单元格为基础获取的最大合并数
                let finalNextIndex;//获取其下第一个不合并单元格的index
                let finalNextKey;//获取其下第一个不合并单元格的值
                for(let i = 0; i < childFilterArr.length; i++){
                    (maxNum>9000||!maxNum)&&(maxNum = $(childFilterArr[i]).prev().attr("rowspan")&&fieldName!="8"?$(childFilterArr[i]).prev().attr("rowspan"):9999);
                    let key = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;//获取下一个单元格的值
                    let nextIndex = i+1;
                    let tdNum = childFilterTextObj[key];
                    let curNum = maxNum<tdNum?maxNum:tdNum;
                    if(canRowspan){
                        for(let j =1;j<=curNum&&(i+j<childFilterArr.length);){//循环获取最终合并数及finalNext的index和key
                            finalNextKey = flag?childFilterArr[i+j].innerHTML:childFilterArr[i+j].textContent;
                            finalNextIndex = i+j;
                            if((key!=finalNextKey&&curNum>1)||maxNum == j){
                                canRowspan = true;
                                curNum = j;
                                break;
                            }
                            j++;
                            if((i+j)==childFilterArr.length){
                                finalNextKey=undefined;
                                finalNextIndex=i+j;
                                break;
                            }
                        }
                        childFilterArr[i].setAttribute("rowspan",curNum);
                        if($(childFilterArr[i]).find("div.rowspan").length>0){//设置td内的div.rowspan高度适应合并后的高度
                            $(childFilterArr[i]).find("div.rowspan").parent("div.layui-table-cell").addClass("rowspanParent");
                            $(childFilterArr[i]).find("div.layui-table-cell")[0].style.height= curNum*38-10 +"px";
                        }
                        canRowspan = false;
                    }else{
                        childFilterArr[i].style.display = "none";
                    }
                    if(--childFilterTextObj[key]==0|--maxNum==0|--curNum==0|(finalNextKey!=undefined&&nextIndex==finalNextIndex)){//||(finalNextKey!=undefined&&key!=finalNextKey)
                        canRowspan = true;
                    }
                }
            }
            //合并数据表格行
            var layuiRowspan = function(fieldNameTmp,index,flag){
                let fieldName = [];
                if(typeof fieldNameTmp == "string"){
                    fieldName.push(fieldNameTmp);
                }else{
                    fieldName = fieldName.concat(fieldNameTmp);
                }
                for(let i = 0;i<fieldName.length;i++){
                    execRowspan(fieldName[i],index,flag);
                }
            }
        }
    });
    //输出模块
    e("list", {})
});